package com.hdu.mockService.handler;

import com.hdu.mockService.annotation.RandomDouble;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

import static com.hdu.mockService.utils.ReflectionUtils.getFieldsByTargetAnnotation;

public class DoubleMockHandler implements IMockHandler {

    @Override
    public void partitionMock(Object mockObj) {
        List<Field> mockDoubleFields = getFieldsByTargetAnnotation(mockObj.getClass(), RandomDouble.class);
        if (CollectionUtils.isEmpty(mockDoubleFields)) {
            return;
        }
        mockDoubleFields.forEach(field -> {
            field.setAccessible(true);
            try {
                double min = field.getAnnotation(RandomDouble.class).min();
                double max = field.getAnnotation(RandomDouble.class).max();
                field.set(mockObj, getRandomDouble(min, max));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    }

    protected Double getRandomDouble(double min, double max) {
        return min + (max - min) * Math.random();
    }

}
